package com.cykj.controller;

import com.cykj.bean.Goods;
import com.cykj.bean.PageConfig;
import com.cykj.bean.Tbluser;
import com.cykj.service.IndexService;
import com.cykj.service.impl.IndexServiceImpl;
import org.apache.ibatis.session.RowBounds;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Controller
// 在加一个 @RequestMapping  成为二级路径
public class IndexController {

    @Autowired
    private IndexService indexServiceImpl;

//    @RequestMapping("/index")
//    @ResponseBody
//    public String index(){
//
//        return "success";
//    }

    //method = RequestMethod.POST限制该请求只能用POST请求
    //@RequestBody  用post请求需要
    @RequestMapping("/login")//请求路径
    @ResponseBody
    public String login(HttpServletRequest request, @RequestBody Tbluser tbluser){
//        ModelAndView modelAndView=new ModelAndView("login");
//        modelAndView.addObject("time", new Date());
//        modelAndView.getModel().put("name","abc");
//        return modelAndView;
//        System.out.println(tbluser.getUname());
//        System.out.println(tbluser.getUpwd());
//        if (userLogin!=null){
//            request.getSession().setAttribute("tbluser",tbluser);
//            return "success";
//        }
//        return "false";
        System.out.println("123456");
        System.out.println("111111");
        return indexServiceImpl.login(tbluser.getUname(),tbluser.getUpwd());

    }

    //注册
    @RequestMapping("/regiest")
    @ResponseBody
//    @Log(module = "方法",action = "regiest",remark = "注册") //日志
    public String Regiest( HttpServletRequest request, @RequestBody Tbluser tbluser  ){
        System.out.println(tbluser.getUname());
        System.out.println(tbluser.getUpwd());
        int regiest=indexServiceImpl.regiest(tbluser);
        if (regiest==1){
            request.getSession().setAttribute("tbluser",tbluser);
            return "success";
        }
        System.out.println(regiest);
        return "fale";
    }


    //用户表格显示
    @RequestMapping("/getUserList")
    @ResponseBody
    public Map<String,Object> getUserList(@RequestBody PageConfig pageConfig){
        Map<String,Object> map = new HashMap<>();
        map.put("pageConfig",pageConfig);
        map.put("count",indexServiceImpl.selectCount());
        map.put("userList",indexServiceImpl.selectUserList2(new RowBounds((pageConfig.getPage() - 1) * pageConfig.getSize(),pageConfig.getSize())));
        return map;
    }


    //用户商品删除
    @RequestMapping("/deleteInfo")
    @ResponseBody
    public Tbluser delete(@RequestBody Tbluser tbluser){
        System.out.println(tbluser.getUid());
        indexServiceImpl.deleteUpdate(String.valueOf(tbluser.getUid()));
        return tbluser;
    }

    //用户信息修改
    @RequestMapping("/updateInfo")
    @ResponseBody
    public Tbluser updateInfo(@RequestBody Tbluser tbluser){
        indexServiceImpl.updateInfo(tbluser.getUname(),tbluser.getIdCard(),tbluser.getAddress(),tbluser.getUid()+"");
        return tbluser;
    }

    //商品查找
    @RequestMapping("/getGoodsList")
    @ResponseBody
    public Map<String,Object> getGoodsList(@RequestBody PageConfig pageConfig){
        return indexServiceImpl.goodsTables(pageConfig);

    }


    //商品删除
    @RequestMapping("/deleteGoods")
    @ResponseBody
    public int deleteGoods(@RequestBody Goods goods){
        return indexServiceImpl.deleteGoods(String.valueOf(goods.getId()));
    }


    //商品修改
    @RequestMapping("/updateGoods")
    @ResponseBody
    public int updateGoods(@RequestBody Goods goods){
        return indexServiceImpl.updateGoods(goods);
    }


    //上传图片
//    @RestController
//    @CrossOrigin
//    public class ElUpload {
//
//       //@Value("${filepath}")
//        public String filePath;
//
//        @RequestMapping("/upload")
//        public String elUpload(MultipartFile file){
//            String fileName = file.getOriginalFilename();
//            System.out.println(fileName);
//            File dest = new File(filePath + fileName);
//            try {
//                file.transferTo(dest);
//                return "上传成功";
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            return "上传失败！";
//        }
//
//    }



    //上传图片
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String doFirst(HttpServletRequest req, MultipartFile uploadFile) throws Exception {
        System.out.println("77788");
        System.out.println(uploadFile.getSize()+"11112223");
        if (uploadFile.getSize() > 0) {
            //获取前半部分路径，建一个名称为upload文件夹
            // 转换成绝对路径
            String path = req.getServletContext().getRealPath("/upload");
            //判断文件夹是否存在，如果不存在则进行创建
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }

            //获取上传文件的后缀名
            String fileType =uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().indexOf("."));

            //获取文件名作为保存到服务器的文件名称
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileName = uuid+fileType;
            // todo 把文件名存入数据库(此步骤省略)

            //完成文件上传
            uploadFile.transferTo(new File(path, fileName));
            System.out.println("sss");
            return "success";
        }
        return "false";
    }


    //可上传文件类型定义
    private List fileTypes = new ArrayList(){{
        add("jpg");
        add("png");
    }
    };

    @RequestMapping("upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws JSONException {
        JSONObject jsonRsult = new JSONObject();
        if (file.isEmpty()){
            jsonRsult.put("code",201);
            jsonRsult.put("msg","请选择文件");
            return jsonRsult.toString();
        }
        String originalFilename = file.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        if (!fileTypes.contains(fileType)){
            jsonRsult.put("code",201);
            jsonRsult.put("msg","仅支持 .jpg .png 文件上传");
            return jsonRsult.toString();
        }
        System.out.println(fileType);
        String path = "R:\\boot\\src\\main\\resources\\tupian\\";
        Path filePath = Paths.get(path + originalFilename);
        try {
            byte[] fileBytes = file.getBytes();
            Files.write(filePath, fileBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        jsonRsult.put("code",0);
        jsonRsult.put("msg","上传成功");
        return jsonRsult.toString();
    }





    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

}
